<% if @user.name %>
  <% content_for :title, t("users.circuitverse.index.title", name: @user.name) %>
  <% set_meta_tags author: @user.name %>
<% else %>
  <% content_for :title, t("users.circuitverse.index.alt_title") %>
  <% set_meta_tags author: nil %>
<% end %>

<% set_meta_tags twitter: {
     card: "summary_large_image",
     title: yield(:title),
     image: {
       src: "#{Rails.configuration.site_url}img/circuitverseBanner2.png"
     }
   } %>

<% set_meta_tags og: {
     title: yield(:title),
     image: "#{Rails.configuration.site_url}img/circuitverseBanner2.png",
     type: "article",
     site_name: Rails.configuration.site_name
   } %>

<div class="container">
  <% if notice %>
  <div class="row" id='alertdiv'>
    <div class="alert alert-success alert-dismissible container text-center">
      <a href="#" class="btn-close" data-bs-dismiss="alert" aria-label="close"></a>
      <h6><%= notice %></h6>
    </div>
  </div>
  <% end %>
  <div class="row center-row users-details-container">
    <div class="row center-row">
      <div class="col-12 col-sm-12 col-md-5 col-lg-5">
        <div class="row center-row">
          <%= image_tag user_profile_picture(@profile.profile_picture), alt: "project.name", class: "center-row search-usersearch-image" %>
        </div>
      </div>
      <div class="col-12 col-sm-12 col-md-7 col-lg-7">
        <h4 class="users-user-name"><%= @profile.name %></h4>
        <div class="search-userdetails-container">
          <p class="search-user-details-text"><%= t("users.circuitverse.member_since_html", member_since: @profile.member_since) %></p>
          <p class="search-user-details-text">
            <% if @profile.educational_institute.present? %>
              <%= t("users.circuitverse.educational_institutes_html", educational_institute: @profile.educational_institute) %>
            <% else %>
              <%= t("users.circuitverse.educational_institutes_html", educational_institute: t("not_entered")) %>
            <% end %>
          </p>
          <p class="search-user-details-text">
            <% if @profile.country_name.blank? %>
              <%= t("users.circuitverse.country_html", country_name: t("not_entered")) %>
            <% else %>
              <%= t("users.circuitverse.country_html", country_name: @profile.country_name) %>
            <% end %>
          </p>
          <% if policy(@user).edit? %>
            <a class="btn primary-button ms-0" href="<%= profile_edit_path(current_user) %>"><%= t("users.circuitverse.index.edit_details") %></a>
          <% end %>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-12 users-circuits-navbar">
      <div class="users-circuits-navbar-buttons">
        <button id="my-circuits" class="btn users-circuits-tab active"><%= t("users.circuitverse.index.my_circuits") %></button>
        <button id="favourite-circuits" class="btn users-circuits-tab users-favourites-tab"><%= t("users.circuitverse.index.favourite_circuits") %></button>
        <button id="collaborator-circuits" class="btn users-circuits-tab users-collaborators-tab"><%= t("users.circuitverse.index.collaborated_circuits") %></button>
      </div>
      <div class="users-circuits-search-container">
      <span><i class="fas fa-search search-icon-dashboard"></i><input type="search" class="users-circuits-search form-control form-input " placeholder="<%= t("users.circuitverse.index.search_circuits") %>"></span>
      </div>
    </div>
  </div>
  <div class="users-circuits-container">
    <div id="my-circuits-div" class="row center-row circuit-page">
      <% if @user.projects.blank? %>
      <div class="col-12">
        <div class="search-no-results-image">
          <%= image_tag "svgs/noProject.svg", alt: "No result image" %>
          <% if current_user == @user %>
            <h6><%= t("users.circuitverse.index.no_projects_heading_html", simulator_new_url: link_to(t("users.circuitverse.index.create_here"), simulator_new_url, class: "anchor-text")) %></h6>
          <% else %>
            <h6><%= t("users.circuitverse.index.no_user_projects", name: @user.name) %></h6>
          <% end %>
        </div>
      </div>
      <% else %>
        <%= render partial: "dashboard", locals: { projects: @user.projects } %>
      <% end %>
    </div>
    <div id="favourite-circuits-div" class="row center-row circuit-page">
      <% if @projects.blank? %>
        <div class="col-12">
          <div class="search-no-results-image">
            <%= image_tag "svgs/noProject.svg", alt: "No result image" %>
            <% if current_user == @user %>
              <h6><%= t("users.circuitverse.index.no_favourites_heading_html", simulator_new_url: link_to(t("users.circuitverse.index.create_here"), simulator_new_url, class: "anchor-text")) %></h6>
            <% else %>
              <h6><%= t("users.circuitverse.index.no_user_favourites", name: @user.name) %></h6>
            <% end %>
          </div>
        </div>
      <% else %>
        <%= render partial: "dashboard", locals: { projects: @projects } %>
      <% end %>
    </div>
    <div id="collaborator-circuits-div" class="row center-row circuit-page">
      <% collaborated_projects = @user.collaborated_projects %>
      <% if collaborated_projects.count == 0 %>
        <div class="col-12">
          <div class="search-no-results-image">
            <%= image_tag "svgs/noProject.svg", alt: "No result image" %>
            <% if current_user == @user %>
              <h6><%= t("users.circuitverse.index.not_a_collaborator") %></h6>
            <% else %>
              <h6><%= t("users.circuitverse.index.user_not_a_collaborator", name: @user.name) %></h6>
            <% end %>
          </div>
        </div>
      <% else %>
        <%= render partial: "dashboard", locals: { projects: collaborated_projects } %>
      <% end %>
    </div>

  </div>
</div>

<script type="application/ld+json">
{
  "@context" : "http://schema.org",
  "@type" : "Article",
  "name" : "<%= @user.name %> - Projects",
  "author" : {
    "@type" : "Person",
    "name" : "<%= @user.name %>"
  }
}
</script>

<%= render partial: "view_project_modal" %>
<script src="https://cdn.jsdelivr.net/npm/fuse.js@6.4.3"></script>
<%# for user projects search %>
<script type="text/javascript">

  function getTitle(circuitDiv) {
      return $('.users-card-name p', circuitDiv)[0].textContent;
  }
  var projects = $('.circuit-card-js'); // collecting all the title tags
  projectList = [];
  projects.each((i, project) => projectList.push({title: getTitle(project), domObj: project}));

  const options = {
    // isCaseSensitive: false,
    // includeScore: false,
    // shouldSort: true,
    // includeMatches: false,
    // findAllMatches: true,
    // minMatchCharLength: 1,
    // location: 0,
    // threshold: 0.6,
    // distance: 100,
    // useExtendedSearch: false,
    // ignoreLocation: false,
    // ignoreFieldNorm: false,
    keys: [
      "title"
    ]
  };

  const fuse = new Fuse(projectList, options);

  // on key up
  $('.users-circuits-search').keyup(() => {
    const searchQuery = $('.users-circuits-search').val().toLowerCase().trim();
    // if searchQuery is not empty
    if(searchQuery) {
      // Mark everything as hidden initially
      projects.hide();
      // Find matches
      var matches = fuse.search(searchQuery);
      var matchMap = {}
      matches.forEach((match, i) => {
          matchMap[match.item.title] = i;
          // mark matches as visible
          $(match.item.domObj).show();
      })
      // Helper function used for sorting cards
      function getSortIndex(circuitDiv) {
        var title = getTitle(circuitDiv);
        if (title in matchMap) return matchMap[title];
        return matches.length;
      }

      // Sort cards
      var dashboards = $('.circuit-page');
      dashboards.each((i, dashboard) => {
        var circuitCards = $(dashboard).children();
        circuitCards.detach().sort((a, b) => {
          a = getSortIndex(a);
          b = getSortIndex(b);
          if (a == b) return 0;
          return a > b ? 1 : -1;
        })
        $(dashboard).append(circuitCards);
      });
    } else { // if searchQuery is empty -> display everything
      projects.show();
    }
  })

</script>

<script type="text/javascript">
  $(function() {
    $('#favourite-circuits-div').hide();
    $('#collaborator-circuits-div').hide();
    var circuitTabs = ['favourite-circuits', 'my-circuits', 'collaborator-circuits'];
    $('.users-circuits-tab').on('click', function (e) {
      if(!$(this).hasClass("active")) {
        var id = this.id;
        $(this).addClass("active");
        circuitTabs.forEach(element => {
          var div = `#${element}-div`;
          if(element == id) {
            $(div).css("display", "flex");
          }
          else {
            $('#' + element).removeClass("active");
            $(div).css("display", "none");
          }
        });
      }});
    $('.previewButton').on('click', function (e) {
        e.preventDefault()
        let project = $(e.currentTarget).data('currentproject').id;
        $("#projectPreview").attr("src","/simulator/" + project.toString() );
        $("#projectModal").tab('show');
    });
    $("#projectModal").on("show.bs.modal", function(e) {
        let projectSlug = $(e.relatedTarget).data('currentproject').slug;
        let projectId = $(e.relatedTarget).data('currentproject').id;
        let authorId = $(e.relatedTarget).data('currentproject').author_id;
        var id = projectSlug ? projectSlug : projectId;
        $(e.currentTarget).find('#project-launch-button').attr("href",
        "/simulator/edit/" + id);
        $(e.currentTarget).find('#project-fork-button').attr("href",
        "/projects/create_fork/" + projectId.toString());
        $(e.currentTarget).find('#project-more-button').attr("href",
        "/users/" + authorId + "/projects/" + id);
    });
  });
</script>
